package com.lap.watchdog.starter.core;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;

import java.util.concurrent.TimeUnit;

public class CaffeineRepeat implements Repeat {

  private final Cache<String, Boolean> cache;

  public CaffeineRepeat() {
    this.cache = Caffeine.newBuilder().expireAfterWrite(1, TimeUnit.HOURS).build();
  }

  @Override
  public boolean isDuplicate(String key, long period) {
    String cacheKey = getCacheKey(key);
    Boolean present = cache.getIfPresent(cacheKey);
    if (present == null) {
      cache.put(cacheKey, true);
      return false;
    }
    return true;
  }

  @Override
  public void delKey(String key) {
    String cacheKey = getCacheKey(key);
    cache.invalidate(cacheKey);
  }
}
